// pages/login/login.js
import Toast from '@vant/weapp/toast/toast';
var config = require('../../config.js')
Page({
  data: {
    show_userinfo: true,
    show_userphone: false,
    setunlockpwd: false,
    openid: '',
    phone: '',
    session_key: '',
    agreePrivacy: false,
  },
  
  onPrivacyChange(e) {
    this.setData({
      agreePrivacy: e.detail.value.includes('agree')
    });
  },

  showPrivacyPolicy() {
    wx.navigateTo({
      url: '../service-agreement/service-agreement',
    });
  },

  tempAccess() {
    console.log('User accessing temporarily without login');
    wx.reLaunch({
      url: '../index/index?tempAccess=true',
    });
  },

  getUserInfo(e){
    if (!this.data.agreePrivacy) {
      wx.showToast({ title: '请先同意隐私政策', icon: 'none' });
      return;
    }
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    var __this = this;
    if (e.detail.errMsg == "getUserInfo:ok")
    {
      console.log('111')
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            console.log(res.code)
            wx.request({
              url: config.url.Login,
              method: 'POST',
              data: {
                'code': res.code,
                'client': config.client
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              success(res) {
                console.log(res.data)
                console.log('openid', res.data.openid)
                console.log('111', e.detail.userInfo)

                if ((res.data.openid != "") && (typeof res.data.openid != 'undefined'))
                {
                  __this.setData({
                    show_userinfo: false,
                    show_userphone: true,
                    openid: res.data.openid,
                    session_key: res.data.session_key,
                  })
                }
               
                try {
                  wx.setStorageSync('userinfo', e.detail.userInfo)
                } catch (e) { } 
                
              },
              fail(err) {
                console.error(err)
                wx.showToast({
                  title: '网络错误，请重试',
                  icon: 'none'
                });
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
            wx.showToast({
              title: '登录失败，请重试',
              icon: 'none'
            });
          }
        }
      })
    }
    console.log('22')
  },
  
  getPhoneNumber(e) {
    if (!this.data.agreePrivacy) {
      wx.showToast({ title: '请先同意隐私政策', icon: 'none' });
      return;
    }
    var _this = this

    if (e.detail.errMsg =="getPhoneNumber:ok" ) 
    {
      wx.login({
        success(res) {
          if (res.code) {
            wx.request({
              url: config.url.getPhone,
              method: 'POST',
              data: {
                'encryptedData': e.detail.encryptedData,
                'iv': e.detail.iv,
                'code': res.code,
                'openid': _this.data.openid,
                'client': config.client,
                 'id': 1
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              success(res) {
                console.log(res.data)
                console.log('333-->', res.data.phoneNumber)
                
                if ((typeof res.data.phoneNumber == 'undefined')) {
                    console.log('444-->', res.data.phoneNumber)
                    Toast.fail('请重新获取！')
                }
                else{
                  _this.setData({
                    show_userinfo: false,
                    show_userphone: false,
                    phone: res.data.phoneNumber,
                    setunlockpwd: true,
                  })

                  try {
                    wx.setStorageSync('phone', res.data.phoneNumber)
                  } catch (e) { }
                }
              },
              fail(err) {
                console.error(err)
                wx.showToast({
                  title: '网络错误，请重试',
                  icon: 'none'
                });
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
            wx.showToast({
              title: '登录失败，请重试',
              icon: 'none'
            });
          }
        }
      })
    }
  },


  getMessage()
  {
    var _this = this
    wx.requestSubscribeMessage({

      tmplIds: [config.TemplateId],

      success: function (res) {

        console.log(res)
        _this.setData({
          show_userinfo: false,
          show_userphone: false,
          // getmessage: false,
          setunlockpwd: true,
        })
        
        // wx.reLaunch({
        //   url: '../index/index?id=' + 1,
        // })
      },

      fail: function (err) {

        console.log(err)

      }

    })
  },

  to_unlock_password() {
    if (this.data.phone !="")
    {
      wx.navigateTo({
        url: '../unlock_password/unlock_password?id=' + this.data.phone,
      })
    }
    else
    {
      wx.showToast({
        title: '手机号码为空',
        icon: 'none',
        duration: 2000
      })
    }
  },

  onLoad: function (options) {
    var userInfo = wx.getStorageSync('userinfo')
    if (userInfo != "")
    {
      this.setData({
        show_userinfo: false,
        show_userphone: true
      })
    }

    var phone = wx.getStorageSync('phone')
    if((phone != "") &&(phone != "")) {
      wx.reLaunch({
        url: '../index/index?id=' + phone,
      })
    }
  },

  onReady: function () {},
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {},
})